#include "clientdialog.h"
#include "ui_clientdialog.h"

ClientDialog::ClientDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ClientDialog)
{
    ui->setupUi(this);
    status = false;
    connect(&tcpsoket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(&tcpsoket,SIGNAL(disconnected()),this,SLOT(onDisconected()));
    connect(&tcpsoket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(&tcpsoket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError()));
}

ClientDialog::~ClientDialog()
{
    delete ui;
}

//发送信息的槽函数
void ClientDialog::on_sendButton_clicked()
{
    //获取用户输入的聊天消息
    QString msg = ui->MessageEdit->text();
    if(msg =="")
    {
        return;
    }
    msg = username + ":" + msg;
    //发送聊天消息
    tcpsoket.write(msg.toUtf8());
    //清空消息输入框
    ui->MessageEdit->clear();
}

//连接服务器的槽函数
void ClientDialog::on_connectButton_clicked()
{
     //如果当前是离线状态，则建立和服务器连接
    if(status == false)
    {
       //获取服务器的IP
        serverIP.setAddress(ui->ServerIpEdit->text());
        //获取服务器的端口
        serverPort = ui->PortEdit->text().toShort();
        //获取聊天室的昵称
        username = ui->usernameEdit->text();
        //向服务器发送连接请求
        //成功发送信号：connected
        //发送失败信号：error
        tcpsoket.connectToHost(serverIP,serverPort);
    }
    //如果当前是在线状态，则断开和服务器的连接
    else
    {
        //向服务器发送离开聊天室的提示消息
        QString msg = username + ":离开了聊天室";
        tcpsoket.write(msg.toUtf8());
        //关闭和服务器的连接，同时发送信号：disconnected
        tcpsoket.disconnectFromHost();
    }
}

//和服务器连接成功时执行的槽函数
void ClientDialog::onConnected()
{
    status = true; //在线状态
    ui->sendButton->setEnabled(true);   //恢复按钮状态
    ui->ServerIpEdit->setEnabled(false);    //禁用IP
    ui->PortEdit->setEnabled(false);        //禁用Port
    ui->usernameEdit->setEnabled(false);    //禁用昵称
    ui->connectButton->setText("离开聊天室");

    //向服务器发送进入聊天室的提示消息
    QString msg = username + ":进入聊天室";
    //ToUtf-8:QString转换QByteArray
    tcpsoket.write(msg.toUtf8());

}

//和服务器断开连接时执行的槽函数
void ClientDialog::onDisconected()
{
    status = false; //在线状态
    ui->sendButton->setEnabled(false);   //禁用按钮状态
    ui->ServerIpEdit->setEnabled(true);    //恢复IP
    ui->PortEdit->setEnabled(true);        //恢复Port
    ui->usernameEdit->setEnabled(true);    //恢复昵称
    ui->connectButton->setText("连接服务器");
}

//接收聊天消息的槽函数
void ClientDialog::onReadyRead()
{
    if(tcpsoket.bytesAvailable())
    {
        //接收消息
        QByteArray buf = tcpsoket.readAll();
        //显示消息
        ui->listWidget->addItem(buf);
        ui->listWidget->scrollToBottom();
    }
}

//网络异常执行的槽函数
void ClientDialog::onError()
{
    //errorString():获取网络异常的原因
    QMessageBox::critical(this,"ERROR",tcpsoket.errorString());
}
